package com.xxyf.service.imp;

import com.xxyf.domain.JwtUtil;
import com.xxyf.emil.Emali;
import com.xxyf.entity.Username;
import com.xxyf.mapper.MenuMapper;
import com.xxyf.mapper.UsernameMapper;
import com.xxyf.service.LogUserDetaImp;
import com.xxyf.service.UsernameService;
import com.xxyf.tools.Code;
import com.xxyf.tools.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author 小小怡飞
 * @Date 2022/8/24 21:09
 * @Version JDK 8
 */
@Service
public class UsernameServiceImp implements UsernameService {
    @Autowired
    private Emali emali;
    @Autowired
    UsernameMapper usernameMapper;
    @Autowired
    private AuthenticationManager manager;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;


    @Override
    public Rest code(String account) {

        if (!StringUtils.hasText(account) && account.matches(
                "^([a-zA-Z]|[0-9])(\\w|\\-)+@[a-zA-Z0-9]+\\.([a-zA-Z]{2,4})$")
        ){
            return new Rest(Code.erro,"不是邮箱");
        }
//        判断是否存在
        Boolean aBoolean = redisTemplate.hasKey(account);
        if (Boolean.TRUE.equals(aBoolean)){
            return new Rest(Code.succeed,"验证码已经发送到邮箱");
        }
        String code = createCode(6);
//        五分钟失效
        redisTemplate.opsForValue().set(account,code,60*5,TimeUnit.SECONDS);
        emali.send("注册验证码",code,account);

        return new Rest(Code.succeed,"验证码已经发送到邮箱");
    }

    static String createCode(Integer count){
        return String.valueOf((int)((Math.random()*9+1)* Math.pow(10,count-1)));
    }
    @Override
    public Rest login(String username, String password) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);

//        传入账户 密码验证权限
        Authentication authenticate = manager.authenticate(authenticationToken);
        if (authenticate==null){
            throw new RuntimeException("错误");
        }

        //获得封装权限类
        LogUserDetaImp principal = (LogUserDetaImp) authenticate.getPrincipal();
//        生成jwt
        String jwt = JwtUtil.createJWT(principal.getUser().getId().toString());

//        传入redis
        try {
            redisTemplate.opsForValue().set("login:"+principal.getUser().getId().toString(),principal,30*60, TimeUnit.SECONDS);
        }catch (Exception e){
            throw new RuntimeException("redis异常");
        }

//        返回键值对
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("token",jwt);
        objectObjectHashMap.put("username",principal.getUser().getUsername());
        objectObjectHashMap.put("id",principal.getUser().getId());
        objectObjectHashMap.put("icon",principal.getUser().getIcon());
        return new Rest(Code.succeed,objectObjectHashMap);
    }
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired

    private MenuMapper mapper;

    /**
     * 注册
     * @param id
     * @param pass
     * @param old
     * @param code
     * @return
     */
    @Transactional
    @Override
    public Rest reg(String id, String pass,String old,String code) {
//        获取验证码
        if (StringUtils.hasText(code)){
            String key = (String) redisTemplate.opsForValue().get(id);
            if (!code.equals(key)){
               return new Rest(Code.erro,"验证码错误");
            }

        }else {
            return new Rest(Code.erro,"验证码为空");
        }
        if (StringUtils.hasText(id) && StringUtils.hasText(pass) && StringUtils.hasText(old)){
            if (pass.equals(old)){
                Username username = new Username();

                username.setPassword(passwordEncoder.encode(pass));
                username.setAccount(id);
                username.setAdminUserName(pass);
                int reg = usernameMapper.insert(username);

                if (reg>0){
                    mapper.role(username.getId());
                    return new Rest(Code.succeed,"注册成功，账号为:"+id+",密码为:"+pass+"请牢记");
                }else {
                    return new Rest(Code.erro,"新建用户失败,账号密码输入错误");
                }
            }else {
                return new Rest(Code.erro,"新建用户失败,两次密码输入不一致");
            }
        }
        return new Rest(Code.erro,"请求错误");
    }

    @Override
    public Rest check(String id) {
        if (StringUtils.hasText(id)){
            String check = usernameMapper.check(id);
            if (!id.equals(check)){
                return new Rest(Code.succeed);
            }else {
                return new Rest(Code.erro,"账号已存在");
            }
        }
        return new Rest(Code.erro,"请求错误");
    }


}
